﻿using Chloe;
using Chloe.MySql;
using System;
using System.Collections.Generic;

namespace JW.ORM
{
    public class DbContextFactory : IDbContextFactory
    {
        private readonly string _conString;

        private readonly Dictionary<string, MySqlContext> _contexts = new Dictionary<string, MySqlContext>();

        public DbContextFactory(string conString)
        {
            this._conString = conString;
        }

        public DbContext CreateDbContext(Type tableType)
        {
            if (_contexts.TryGetValue(this._conString, out var context))
                return context;

            context = new MySqlContext(new MySqlConnectionFactory(this._conString));
            _contexts[this._conString] = context;
            return context;
        }

        public void Dispose()
        {
            foreach (var context in _contexts.Values)
            {
                context.Dispose();
            }
        }
    }
}